package leetcode.weekly.week333;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import leetcode.helper.H;

//Solution3Test
public class Solution3 {

	int mod = (int) 1e9 + 7;

	public int squareFreeSubsets(int[] nums) {
		boolean[] h = new boolean[31];
		h[1] = true;
		for (int i = 2; i <= 30; i++) {
			h[i] = f(i);
		}
		List<Integer> list = primes(31);
		Integer[] prime = list.toArray(new Integer[] {});
		int size = prime.length;
		int[] dp = new int[1 << size];
		for (int num : nums) {
			if (!h[num]) {
				continue;
			}
			int status = 0;
			for (int i = 0; i < size; i++) {
				if (num % prime[i] == 0) {
					status |= 1 << i;
				}
			}
			for (int i = (1 << size) - 1; i >= 0; i--) {
				if ((i & status) == 0) {
					dp[i | status] += dp[i];
					dp[i | status] %= mod;
				}
			}
			dp[status] += 1;
			dp[status] %= mod;
		}
		long ans = 0;
		for (int i = 0; i < (1 << size); i++) {
			ans += dp[i];
			ans %= mod;
		}
		return (int) ans;
	}

	public List<Integer> primes(int n) {
		boolean[] dp = new boolean[n];
		List<Integer> primes = new ArrayList<>();
		for (int i = 2; i < n; i++) {
			if (!dp[i]) {
				primes.add(i);
			}
			for (int j = 0; j < primes.size(); j++) {
				int prime = primes.get(j);
				if (prime * i >= n) {
					break;
				}
				dp[prime * i] = true;
				if (i % prime == 0) {
					break;
				}
			}
		}
		return primes;
	}

	private boolean f(int num) {
		int ans = 0;
		for (int i = 2; i <= num; i++) {
			while (num % i == 0) {
				int add = 1 << i;
				if ((ans & add) == add) {
					return false;
				}
				ans |= add;
				num /= i;
			}
		}
		return true;
	}

}
